package com.auto.learning.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.net.MspClient;
import com.auto.learning.R;
import com.auto.learning.event.Handle;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.SharedPreferencesUtils;

public class RegeditActivity extends Activity implements OnClickListener{
	
	private final static int GET_CODE_SUCCESS = 1;
	private final static int GET_CODE_FAIL = 2;
	private final static int VERY_SUCCESS = 3;
	private final static int CHECK_BIND_SUCCESS = 4;
	private final static int CHECK_BIND_FAIL = 5;
	private final static int USER_BIND_TEL_SUCCESS = 6;
	private String veryPhone = "";
	
	private LinearLayout activity_base_back;
	private int type = 1; //1为新用户注册，2为手机验证,3为绑定账号
	private TextView tv_title,tv_submit,tv_code;
	private EditText et_phone,et_code;
	private ImageView image_backgroup;
	
	int totalTime = 60;
	
	private Handle handle = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GET_CODE_SUCCESS:
				et_phone.setEnabled(false);
				tv_code.setEnabled(false);
				handle.postDelayed(runnable, 1000);
				break;
			case GET_CODE_FAIL:
				CommonMethod.makeNotice(RegeditActivity.this, msg.obj.toString());
				break;
			case VERY_SUCCESS:
				Intent intent = new Intent(RegeditActivity.this, SetPasswordActivity.class);
				intent.putExtra("telCode", msg.obj.toString());
				intent.putExtra("tel", veryPhone);
				intent.putExtra("type", type);
				startActivity(intent);
				finish();
				break;
			case CHECK_BIND_SUCCESS:
				CheckBindInfo result = (CheckBindInfo) msg.obj;
				if (result != null) {
					CommonMethod.makeNotice(RegeditActivity.this, "绑定成功");
					/*if (result.getNeedPwd() == 1) {
						Intent res_intent = new Intent();
						res_intent.putExtra("user_tel", result.getTel());
						setResult(210,res_intent);
						finish();
					} else if (result.getNeedPwd() == 2){  //
						Intent new_intent = new Intent(RegeditActivity.this, SetPasswordActivity.class);
						new_intent.putExtra("telCode", result.getTelCode());
						new_intent.putExtra("tel", result.getTel());
						new_intent.putExtra("type", type);
						startActivityForResult(new_intent,120);
					}*/
					Intent res_intent = new Intent();
					res_intent.putExtra("user_tel", result.getTel());
					setResult(210, res_intent);
					finish();
				}
				break;
			case CHECK_BIND_FAIL:
				CommonMethod.makeNotice(RegeditActivity.this, msg.obj.toString());
				break;
			}
		};
	};
	
	Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			if (totalTime > 0) {
				tv_code.setText("重新获取"+totalTime+"s");
				totalTime--;
				handle.postDelayed(this, 1000);
			}else {
				totalTime = 60;
				et_phone.setEnabled(true);
				tv_code.setEnabled(true);
				tv_code.setText("获取验证码");
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regedit_activity);
		initView();
		TemporaryVariable.activities.push(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		TemporaryVariable.activities.removeElement(this);
		super.onDestroy();
	}
	
	private void initView(){
		type = getIntent().getIntExtra("type", 0);
		activity_base_back = (LinearLayout) findViewById(R.id.activity_base_back);
		activity_base_back.setOnClickListener(this);
		image_backgroup = (ImageView) findViewById(R.id.image_backgroup);
		image_backgroup.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.login_bg));
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_submit = (TextView) findViewById(R.id.tv_submit);
		if (type == 1) {
			tv_title.setText("新用户注册");
			tv_submit.setText("下一步");
		}else if (type == 2) {
			tv_title.setText("手机验证");
			tv_submit.setText("验证");
		}else if (type == 3) {
			tv_title.setText("绑定手机号");
//			tv_submit.setText("下一步");
			tv_submit.setText("绑定");
		}
		tv_code = (TextView) findViewById(R.id.tv_code);
		et_phone = (EditText) findViewById(R.id.et_phone);
		et_code = (EditText) findViewById(R.id.et_code);
		
		tv_code.setOnClickListener(this);
		tv_submit.setOnClickListener(this);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 120 && resultCode == 110) {
			setResult(211);
			finish();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_base_back:
			finish();
			break;
		case R.id.tv_code:
			String phone = et_phone.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				CommonMethod.makeNotice(this, getResources().getString(R.string.text_login_phone));
				et_phone.setFocusable(true);
				return;
			}
			if (CommonMethod.regExpPhone(phone)) {
				veryPhone = phone;
				getVerCode(phone);
			}else {
				CommonMethod.makeNotice(this, getResources().getString(R.string.text_login_phone_reg));
			}
			break;
		case R.id.tv_submit:
			String code = et_code.getText().toString();
			if (TextUtils.isEmpty(code)) {
				CommonMethod.makeNotice(this, "请输入验证码");
				et_code.setFocusable(true);
				return;
			}
			if (type == 3) {
				veryBindCode(code);
			}else {
				veryCode(code);
			}
			break;
		}
	}
	
	
	
	
	/**
	 * 获取手机验证码
	 */
	public void getVerCode(final String tel) {
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				HttpRequestHelper.getVerCode(RegeditActivity.this, handle, tel, type, GET_CODE_SUCCESS, GET_CODE_FAIL);
				
				/*String err = "";
				int isOK = 1;
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair(HttpCommonInfo.REQ_CODE_CODETYPE,String.valueOf(type)));
					params.add(new BasicNameValuePair(HttpCommonInfo.REQ_CODE_TEL, tel));
					HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.CODE, params, RegeditActivity.this);
					String result = HttpHelper.entity2String(entity);
					JSONObject jObject = new JSONObject(parseResultJson(result));
					int resultCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
					if (resultCode == 0) {
						isOK = 0;
					} else {
						isOK = 1;
						err = jObject.getString(HttpCommonInfo.RESULT_MSG);
					}
				} catch (ClientProtocolException e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} catch (IOException e) {
					err = getResources().getString(R.string.connect_err_io);
					isOK = 1;
				} catch (Exception e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} finally {
					switch (isOK) {
					case 0:
						handle.sendEmptyMessage(GET_CODE_SUCCESS);
						break;
					case 1:
						handle.obtainMessage(GET_CODE_FAIL, err).sendToTarget();
						break;
					}
				}*/
			}
		});
	}
	
	public void veryCode(final String telCode){

		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				String err = "";
				int isOK = 1;
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("tel", veryPhone));
					params.add(new BasicNameValuePair("code", telCode));
					params.add(new BasicNameValuePair("checkType",String.valueOf(type)));
					HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.CHECK_CODE, params, RegeditActivity.this);
					String result = HttpHelper.entity2String(entity);
					JSONObject jObject = new JSONObject(parseResultJson(result));
					int resultCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
					if (resultCode == 0) {
						isOK = 0;
						
					} else {
						isOK = 1;
						err = jObject.getString(HttpCommonInfo.RESULT_MSG);
					}
				} catch (ClientProtocolException e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} catch (IOException e) {
					err = getResources().getString(R.string.connect_err_io);
					isOK = 1;
				} catch (Exception e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} finally {
					switch (isOK) {
					case 0:
						handle.obtainMessage(VERY_SUCCESS, telCode).sendToTarget();
						break;
					case 1:
						handle.obtainMessage(GET_CODE_FAIL, err).sendToTarget();
						break;
					}
				}
			}
		});
	}
	
	/**
	 * 绑定手机号时验证
	 * @param telCode
	 */
	public void veryBindCode(final String telCode){

		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				String jsonData_result = "";
				String err = "";
				int isOK = 1;
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("tel", veryPhone));
					params.add(new BasicNameValuePair("code", telCode));
					params.add(new BasicNameValuePair("userId",String.valueOf(SharedPreferencesUtils.getParam(RegeditActivity.this, HttpRequestHelper.USERID, 0))));
					HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.TEL_BIND_CHECK, params, RegeditActivity.this);
					String result = HttpHelper.entity2String(entity);
					JSONObject jObject = new JSONObject(parseResultJson(result));
					int resultCode = jObject.getInt(HttpCommonInfo.RESULT_CODE);
					if (resultCode == 0) {
						isOK = 0;
						jsonData_result = CommonMethod.parseDataJson(result);
					} else {
						isOK = 1;
						err = jObject.getString(HttpCommonInfo.RESULT_MSG);
					}
				} catch (ClientProtocolException e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} catch (IOException e) {
					err = getResources().getString(R.string.connect_err_io);
					isOK = 1;
				} catch (Exception e) {
					err = getResources().getString(R.string.connect_err_unkonw);
					isOK = 1;
				} finally {
					switch (isOK) {
					case 0:
						Message message = new Message();
						CheckBindInfo info = new CheckBindInfo();
						try {
							JSONObject jsonObject = new JSONObject(jsonData_result);
							int needPwd = jsonObject.getInt("needPwd");
							String tel = jsonObject.getString("tel");
							info.setTelCode(telCode);
							info.setTel(tel);
							info.setNeedPwd(needPwd);
						} catch (JSONException e) {
							e.printStackTrace();
						}
						message.obj = info;
						message.what = CHECK_BIND_SUCCESS;
						handle.sendMessage(message);
//						handle.obtainMessage(CHECK_BIND_SUCCESS, telCode).sendToTarget();
						break;
					case 1:
						handle.obtainMessage(CHECK_BIND_FAIL, err).sendToTarget();
						break;
					}
				}
			}
		});
	}
	
	public String parseResultJson(String result) throws JSONException {
		JSONObject jObject = new JSONObject(result);
		result = jObject.getString(HttpCommonInfo.RESULT);
		return result;
	}
	
	public class CheckBindInfo{
		private String telCode;
		private int needPwd;
		private String tel;
		public String getTelCode() {
			return telCode;
		}
		public void setTelCode(String telCode) {
			this.telCode = telCode;
		}
		public int getNeedPwd() {
			return needPwd;
		}
		public void setNeedPwd(int needPwd) {
			this.needPwd = needPwd;
		}
		public String getTel() {
			return tel;
		}
		public void setTel(String tel) {
			this.tel = tel;
		}
	}
	
}
